package com.luck.easyfoodbatch.ui;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.DemoHelper;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.custom.FlowLayout;
import com.luck.easyfoodbatch.db.FindDB;
import com.luck.easyfoodbatch.db.Hits;
import com.luck.easyfoodbatch.db.HitsDB;
import com.luck.easyfoodbatch.db.PlaceDB;
import com.luck.easyfoodbatch.dialog.CustomDialog;
import com.luck.easyfoodbatch.mvp.home.HotKeywordsModel;
import com.luck.easyfoodbatch.mvp.home.HotKeywordsPresenter;
import com.luck.easyfoodbatch.mvp.home.HotKeywordsView;
import com.luck.easyfoodbatch.mvp.model.HotKeywordsM;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchActivity extends BaseActivity implements HotKeywordsView {

    @BindView(R.id.left_back)
    ImageButton leftBack;
    @BindView(R.id.input_search_query)
    EditText inputSearchQuery;
    @BindView(R.id.button_search)
    ImageButton buttonSearch;
    @BindView(R.id.searchBarContainer)
    RelativeLayout searchBarContainer;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.tv_tag_lately)
    TextView tvTagLately;
    @BindView(R.id.tv_tag_search)
    TextView tvTagSearch;
    @BindView(R.id.tv_tag_region)
    TextView tvTagRegion;
    @BindView(R.id.flow_region)
    FlowLayout flow_region;
    @BindView(R.id.flow_search_hist)
    FlowLayout flow_search_hist;
    @BindView(R.id.flow_search)
    FlowLayout flow_search;
    @BindView(R.id.tv_more)
    TextView tv_more;
    @BindView(R.id.ll_del)
    LinearLayout llDel;
    @BindView(R.id.tv_search_hist)
    TextView tv_search_hist;
    @BindView(R.id.tv_flow_search)
    TextView tv_flow_search;
    private HotKeywordsModel keywordsModel;
    private LayoutInflater mInflater;
    private HitsDB hitsDB;
    private List<String> mValues = new ArrayList<>();
    private List<String> mData = new ArrayList<>();
    private PlaceDB placeDB;
    private List<Hits> hits = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        App.getInstance().addActivity(SearchActivity.this);
        ButterKnife.bind(this);
        hitsDB = new HitsDB(this);
        placeDB = new PlaceDB(this);
        mInflater = LayoutInflater.from(this);
        initDataRegion();
        keywordsModel = new HotKeywordsPresenter(this, mContext);
        keywordsModel.getHotKeywords();
        inputSearchQuery.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    llDel.setVisibility(View.VISIBLE);
                } else {
                    llDel.setVisibility(View.GONE);
                }
            }
        });

        inputSearchQuery.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!Tools.isNull(inputSearchQuery.getText().toString().trim())) {
                        String keywords = inputSearchQuery.getText().toString().trim();
                        // 先隐藏键盘
                        hideKeyboard(inputSearchQuery);
                        Bundle bundle = new Bundle();
                        bundle.putString("keywords", keywords);
                        startAct(ShopListActivity.class, bundle);
                        hitsDB.saveHitsList(keywords);
                    } else {
                        T.showToast(mContext, "请输入关键字~");
                    }
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        hits = hitsDB.getByAllList();
        boolean isData = hits.size() == 0 ? true : false;
        if (isData) {
            tv_search_hist.setVisibility(View.VISIBLE);
            flow_search_hist.setVisibility(View.GONE);
        } else {
            tv_search_hist.setVisibility(View.GONE);
            flow_search_hist.setVisibility(View.VISIBLE);
        }
        initDataHistos();
    }

    /**
     * 设置热门地区数据
     */
    public void initDataRegion() {
        for (int i = 0; i < mValues.size(); i++) {
            final TextView tv = (TextView) mInflater.inflate(
                    R.layout.search_label_tv, flow_region, false);
            tv.setText(mValues.get(i));
            //点击事件
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 先隐藏键盘
                    String content = tv.getText().toString().trim();
                    String byId = placeDB.selectNameById(content);
                    hideKeyboard(inputSearchQuery);
                    Bundle bundle = new Bundle();
                    bundle.putString("country_id", byId);
                    startAct(ShopListActivity.class, bundle);
                }
            });
            flow_region.addView(tv);//添加到父View
        }
    }

    /**
     * 设置热门搜索数据
     */
    public void initDataSearch() {
        flow_search.removeAllViews();
        if (mData.size() > 0) {
            flow_search.setVisibility(View.VISIBLE);
            tv_flow_search.setVisibility(View.GONE);
        } else {
            tv_flow_search.setVisibility(View.VISIBLE);
            flow_search.setVisibility(View.GONE);
        }
        for (int i = 0; i < mData.size(); i++) {
            final TextView tv = (TextView) mInflater.inflate(
                    R.layout.search_label_tv, flow_search, false);
            tv.setText(mData.get(i));
            //点击事件
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 先隐藏键盘
                    hideKeyboard(inputSearchQuery);
                    Bundle bundle = new Bundle();
                    bundle.putString("keywords", tv.getText().toString().trim());
                    startAct(ShopListActivity.class, bundle);
                    hitsDB.saveHitsList(tv.getText().toString().trim());
                }
            });
            flow_search.addView(tv);//添加到父View
        }
    }

    /**
     * 设置搜索历史数据
     */
    public void initDataHistos() {
        flow_search_hist.removeAllViews();
        for (Hits item : hits) {
            final TextView tv = (TextView) mInflater.inflate(
                    R.layout.search_label_tv, flow_search_hist, false);
            tv.setText(item.getHits_name());
            //点击事件
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 先隐藏键盘
                    hideKeyboard(inputSearchQuery);
                    Bundle bundle = new Bundle();
                    bundle.putString("keywords", tv.getText().toString().trim());
                    startAct(ShopListActivity.class, bundle);
                }
            });
            tv.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    String keywords = ((TextView) view).getText().toString().trim();
                    showDeleteDialog(keywords);
                    return true;
                }
            });
            flow_search_hist.addView(tv);//添加到父View
        }
    }

    /**
     * 删除搜索关键字
     */
    private void showDeleteDialog(final String keywords) {
        final CustomDialog dialog = new CustomDialog(mContext, App.screenWidth * 3 / 4,
                App.screenHeight / 4, R.layout.wind_base_dialog_xml, R.style.Theme_dialog);
        Button btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
        Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
        TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
        tv_content.setText("确定删除此搜索历史吗？");
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean dbHits = hitsDB.deleteDbHits(keywords);
                if (dbHits) {
                    hits = hitsDB.getByAllList();
                    initDataHistos();
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    @OnClick({R.id.left_back, R.id.tv_search, R.id.tv_more, R.id.ll_del})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_del:
                inputSearchQuery.setText("");
                break;
            case R.id.left_back:
                finish();
                break;
            case R.id.tv_search:
                String keywords = inputSearchQuery.getText().toString().trim();
                if (!Tools.isNull(keywords)) {
                    // 先隐藏键盘
                    hideKeyboard(inputSearchQuery);
                    Bundle bundle = new Bundle();
                    bundle.putString("keywords", keywords);
                    startAct(ShopListActivity.class, bundle);
                    hitsDB.saveHitsList(keywords);
                } else {
                    T.showToast(mContext, "请输入搜索关键字~");
                }
                break;
            case R.id.tv_more:
                startAct(SelectionPointActivity.class);
                break;
        }
    }

    @Override
    public void getHotKeywordsSuccess(HotKeywordsM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                HotKeywordsM.DataBean data = model.getData();
                mData = data.getKeywords();
                mValues = data.getCountry();
                data.getCountry();
                initDataSearch();
                initDataRegion();
            }
        }
    }
}
